//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    url: '',
    data_size: 300, //获取图片量
    results: [], //封装获取数据
    page: 1, //当前页数
    pageSize: 18, //每页数据大小
    hasMoreData: true, //上拉的时候上拉时是否还有数据
    contentlist: [], ////封装展示数据
    refresh: null, //刷新按钮动画
    angle: 0, //刷新图标旋转角度
    currentTab: 0, //tab切换
    floorstatus: true, //初始隐藏回到顶部图标
    floorstatus1: true, //初始隐藏回到顶部图标
    filePath: [], //保存到本地的图片
    collcetData: [], //收藏页面展示的数据
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  //缓存图片数据
  getInfo: function(message) {
    var that = this
    var results = that.data.results;
    var page = that.data.page
    var pageSize = that.data.pageSize
    var data_size = that.data.data_size
    var contentlistTem = that.data.contentlist

    wx.showNavigationBarLoading() //当前页面显示加载动画
    wx.showLoading({
      title: message,
    })
    wx.stopPullDownRefresh()
    //判断加载图片数量
    if (results.length > 0) {
      wx.hideNavigationBarLoading() //在当前页面隐藏导航条加载动画
      setTimeout(function() {
        wx.hideLoading()
      }, 500) //隐藏 loading 提示框
      if (page == 1) {
        var contentlistTem = []
      }
      var contentlist = []
      var resulte2 = []
      var n = 0
      // console.log(contentlist)
      //如果图片剩余量大于页面展示量
      if (results.length > pageSize) {
        var value = wx.getStorageInfoSync()
        var collcetKeys = value.keys
        var keylength = collcetKeys.length
        var a = 0
        //判断转存图片并判断是否收藏
        var photoCollcet = wx.getStorageSync("photoCollcet")
        for (var i = 0; i < pageSize; i++) {
          contentlist[i] = results[i]
          var url = contentlist[i].img
          if (photoCollcet) {
            var isCollcet = photoCollcet.indexOf(url)
            if (isCollcet != -1) {
              contentlist[i].collect = true
            } else {
              contentlist[i].collect = false
            }
          } else {
            contentlist[i].collect = false
          }
          a++
          console.log(a)
          //后续优化内容：将图片储存到某一数组，在缓存在本地   
        }
        contentlistTem = contentlistTem.concat(contentlist)
        // contentlistTem = that.ifDefind(contentlistTem)
        // console.log(resulte2)
        that.setData({
          hasMoreData: true,
          contentlist: contentlistTem,
          page: page + 1
        })
        console.log("当前页面图片显示数量" + that.data.contentlist.length)
        for (var i = pageSize; i < results.length; i++) {
          resulte2[n] = results[i]
          n++
        }
        that.setData({
          results: resulte2,
        })
      } else { //如果图片剩余量小于页面展示量
        var value = wx.getStorageInfoSync()
        var collcetKeys = value.keys
        var keylength = collcetKeys.length
        //判断转存图片并判断是否收藏
        var photoCollcet = wx.getStorageSync("photoCollcet")
        for (var i = 0; i < results.length; i++) {
          var url = results[i].img
          if (photoCollcet) {
            var isCollcet = photoCollcet.indexOf(url)
            if (isCollcet != -1) {
              results[i].collect = true
            } else {
              results[i].collect = false
            }
          } else {
            results[i].collect = false
          }
          console.log(0)

        }
        contentlistTem = contentlistTem.concat(results)
        // contentlistTem = that.ifDefind(contentlistTem)
        that.setData({
          hasMoreData: false,
          contentlist: contentlistTem
        })
        console.log("当前页面图片显示数量" + that.data.contentlist.length)
      }
      // console.log(that.data.contentlist)
    }
  },
  onLoad: function() {
    var that = this
    var data_size = that.data.data_size
    var results = []
    that.refreshCollcet()
    wx.request({
      url: 'https://api.apiopen.top/getImages',
      data: {
        count: data_size
      },
      success: function(res) {
        results = that.ifDefind(res.data.result)
        // var value = wx.getStorageInfoSync()
        // var collcetKeys = value.keys
        // var keylength = collcetKeys.length
        // for (var i = 0; i < results.length; i++) {
        //   var url = results[i].img
        //   for (var j = 0; j < keylength; j++) {
        //     if (url == wx.getStorageSync(collcetKeys[j])) {
        //       results[i].collect = true
        //       break
        //     } else {
        //       results[i].collect = false
        //     }
        //     console.log(0)
        //   }
        // }
        that.setData({
          results: results
        })
        that.getInfo('正在加载数据')
      },
      fail: function() {
        wx.showToast({
          title: '图片加载失败，请检测网络',
          icon: 'none'
        })
      }
    })
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  //轮播图点击预览
  imgYu: function(event) {
    var that = this;
    //图片预览
    var data = that.data.contentlist;
    var n = 0
    var list = []
    // console.log(data)
    for (var i in data) {
      list[n] = data[i].img
      n++
    }
    console.log("放大了图片" + event.currentTarget.dataset.src)
    wx.previewImage({
      current: event.currentTarget.dataset.src, // 当前显示图片的http链接
      urls: list // 需要预览的图片http链接列表,
    })
  },
  imgYu1: function(event) {
    var that = this;
    //图片预览
    var data = that.data.collcetData;
    var n = 0
    // console.log(data)
    console.log("放大了图片" + event.currentTarget.dataset.src)
    wx.previewImage({
      current: event.currentTarget.dataset.src, // 当前显示图片的http链接
      urls: data // 需要预览的图片http链接列表,
    })
  },
  //刷新
  refreshs: function() {
    this.data.page = 1
    var _this = this
    var results = []
    var data_size = _this.data.data_size
    wx.request({
      url: 'https://api.apiopen.top/getImages',
      data: {
        count: data_size
      },
      success: function(res) {
        results = _this.ifDefind(res.data.result)
        _this.setData({
            results: results,
            page: 1,
            contentlist: [],
          }),
          _this.getInfo('正在加载数据')
      },
      fail: function() {
        wx.showToast({
          title: '刷新失败，请检测网络',
          icon: 'none'
        })
      }
    })
    console.log("刷新了图片")
  },
  //下载图片按钮
  download: function(e) {
    var that = this
    let url = e.target.dataset.id
    wx.showModal({
      title: '提示',
      content: '确认下载图片',
      success: function(res) {
        if (res.confirm) {
          console.log("用户点击确定")
          wx.showToast({
            icon: 'loading',
            title: '正在保存图片',
            duration: 1000
          })
          //判断用户是否授权"保存到相册"
          wx.getSetting({
            success(res) {
              //没有权限，发起授权
              if (!res.authSetting['scope.writePhotosAlbum']) {
                wx.authorize({
                  scope: 'scope.writePhotosAlbum',
                  success() { //用户允许授权，保存图片到相册
                    console.log("用户允许授权")
                    that.saveImage(url);
                  },
                  fail() { //用户点击拒绝授权，跳转到设置页，引导用户授权
                    console.log("用户拒绝授权")
                    wx.showModal({
                      title: '请授权',
                      content: '若不授权，将无法保存图片',
                      showCancel: true,
                      cancelText: '不授权',
                      cancelColor: '#999',
                      confirmText: '授权',
                      confirmColor: '#f94218',
                      success(res) {
                        if (res.confirm) {
                          console.log('用户点击授权')
                          wx.openSetting({
                            success(res) {}
                          })
                        } else if (res.cancel) {
                          console.log('用户点击取消')
                        }
                      }
                    })
                  }
                })
              } else { //用户已授权，保存到相册
                console.log("用户已授权")
                that.saveImage(url);
              }
            }
          })
        } else {
          console.log('用户点击取消')
        }

      }
    })
  },
  //保存图片函数
  saveImage(url) {
    wx.downloadFile({
      url: url,
      success(res) {
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              wx.showToast({
                title: '保存成功',
                icon: "success",
                duration: 1000
              })
              console.log("保存成功")
            }
          })
        } else {
          wx.showToast({
            title: '图片错误，保存失败',
            icon: "none",
            duration: 1000
          })
          console.log("保存失败")
        }
      }
    })
  },
  // 获取滚动条当前位置
  onPageScroll: function(e) {
    var that = this
    var currentTab = that.data.currentTab
    if (currentTab == 0) {
      if (e.detail.scrollTop > 200) {
        this.setData({
          floorstatus: false
        });
      } else {
        this.setData({
          floorstatus: true
        });
      }
    } else {
      if (e.detail.scrollTop > 200) {
        this.setData({
          floorstatus1: false
        });
      } else {
        this.setData({
          floorstatus1: true
        });
      }
    }

  },
  //回到顶部
  goTop: function(e) { // 一键回到顶部
    // if (wx.pageScrollTo) {
    //   wx.pageScrollTo({
    //     scrollTop: 0
    //   })
    //   console.log("回到了顶部")
    // } else {
    //   wx.showModal({
    //     title: '提示',
    //     content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
    //   })
    // }
    this.setData({
      topNum: 0
    });
  },
  //判断空图
  ifDefind: function(contentlistTem) {
    var i = 0
    while (i < contentlistTem.length) {
      if (contentlistTem[i].img.charAt(7) == 7 || contentlistTem[i].img.charAt(7) == "a" || contentlistTem[i].img.charAt(8) == "i") {
        contentlistTem.splice(i, 1)
      } else {
        i++
      }
    }
    console.log("去掉了空白图片")
    return contentlistTem
  },
  //刷新
  refresh: function() {
    // var angle = this.data.angle
    // angle = angle + 360
    let that = this
    var animation = wx.createAnimation({})
    animation.rotate(180).step()
    this.setData({
      refresh: animation.export(),
      // angle : angle      
    })
    that.goTop()
    that.refreshs()
    var timer = setTimeout(() => {
      animation.rotate(-180).step()
      this.setData({
        refresh: animation.export(),
      })
    }, 300)
  },
  //tab切换
  swichNav: function(e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current,
      })
    }
  },
  swiperChange: function(e) {
    var that = this
    if (e.detail.current == 1) {
      that.refreshCollcet()
    }
    that.setData({
      currentTab: e.detail.current,
    })

  },
  //上拉触底事件的处理函数
  loadMore: function() {
    var that = this
    var currentTab = that.data.currentTab
    if (currentTab != 1) {
      wx.getNetworkType({ //判断是否有网络
        success: function(res) {
          if (res.networkType != 'none') {
            if (that.data.hasMoreData) {
              that.getInfo('加载更多数据')
            } else {
              wx.showToast({
                title: '没有更多图片了，刷新试试',
                icon: 'none'
              })
            }
          } else {
            wx.showToast({
              title: '加载失败，请检测网络',
              icon: 'none'
            })
          }
        },
      })
    }
  },
  //收藏按钮
  collect: function(e) {
    var that = this
    var url = e.target.dataset.url
    var isCollcet = false
    var keys = wx.getStorageInfoSync().keys
    var key = ""
    // var id = e.target.dataset.id + ""
    // var value = wx.getStorageSync(id)
    var contentlist = that.data.contentlist
    let index = contentlist.findIndex(item => item.img == e.target.dataset.url);

    //判断是否缓存过图片
    var isphotoCollcet = wx.getStorageSync("photoCollcet")
    if (isphotoCollcet) { //缓存过就得到缓存的数据

      var photoCollcets = isphotoCollcet
      var isCollcetThis = photoCollcets.indexOf(url)
      if (isCollcetThis == -1) { //没有收藏过，就加入到缓存
        try {
          photoCollcets.push(url)
          wx.setStorageSync("photoCollcet", photoCollcets)
          contentlist[index].collect = true
          that.setData({
            contentlist: contentlist
          })
          wx.showToast({
            title: '已收藏',
            icon: 'none'
          })
        } catch (e) {
          wx.showToast({
            title: '收藏失败',
            icon: 'none'
          })
        }
      } else { //收藏过，就取消收藏
        try {
          photoCollcets.splice(isCollcetThis, 1)
          wx.setStorageSync("photoCollcet", photoCollcets)
          contentlist[index].collect = false
          that.setData({
            contentlist: contentlist
          })
          wx.showToast({
            title: '已取消收藏',
            icon: 'none'
          })
        } catch (e) {
          wx.showToast({
            title: '取消收藏失败',
            icon: 'none'
          })
        }
      }
    } else { //还没有收藏的图片
      var photoCollcet = []
      photoCollcet.push(url)
      try {
        wx.setStorageSync("photoCollcet", photoCollcet)
        contentlist[index].collect = true
        that.setData({
          contentlist: contentlist
        })
        wx.showToast({
          title: '已收藏',
          icon: 'none'
        })
      } catch (e) {
        wx.showToast({
          title: '收藏失败',
          icon: 'none'
        })
      }
    }
    // //遍历缓存数据，查看对应图片是否在缓存内
    // for (var i = 0; i < keys.length; i++) {
    //   if (url == wx.getStorageSync(keys[i])) { //缓存中含有该图片
    //     key = keys[i]
    //     isCollcet = true
    //     break
    //   }
    // }
    // if (isCollcet) { //判断是否已收藏过
    //   //已收藏便取消收藏（从缓存中删除）
    //   try {
    //     wx.removeStorageSync(key)
    //     contentlist[index].collect = false
    //     that.setData({
    //       contentlist: contentlist
    //     })
    //     wx.showToast({
    //       title: '已取消收藏',
    //       icon: 'none'
    //     })
    //   } catch (e) {
    //     wx.showToast({
    //       title: '取消收藏失败',
    //       icon: 'none'
    //     })
    //   }
    // } else { //未收藏便添加进收藏（加入缓存） 
    //   //给予它缓存的key
    //   if ((keys.length == 2 && wx.getStorageSync("book")) || keys.length == 1) {
    //     var id = "1"
    //   } else {
    //     if (wx.getStorageSync("book")) {
    //       var n = keys.length - 3
    //     } else {
    //       var n = keys.length - 2
    //     }
    //     var id = (parseInt(keys[n]) + 1) + ""
    //   }
    //   try {
    //     wx.setStorageSync(id, url)
    //     contentlist[index].collect = true
    //     that.setData({
    //       contentlist: contentlist
    //     })
    //     wx.showToast({
    //       title: '已收藏',
    //       icon: 'none'
    //     })
    //   } catch (e) {
    //     wx.showToast({
    //       title: '收藏失败',
    //       icon: 'none'
    //     })
    //   }
    // }
  },
  //更新收藏夹数据的函数
  refreshCollcet: function() {
    var that = this
    //如果用户点击的是收藏页面，则获取缓存中的数据
    var isphotoCollcet = wx.getStorageSync("photoCollcet")
    var collcetData = []
    if (isphotoCollcet) { //缓存过就得到缓存的数据
      for (var n = isphotoCollcet.length - 1, m = 0; n >= 0; n--, m++) {
        collcetData[m] = isphotoCollcet[n]
      }
      that.setData({
        collcetData: collcetData
      })
    } else {
      wx.showToast({
        title: '收藏夹中还没有图片，快去图库里逛逛吧',
        icon: 'none'
      })
    }
    // var collectData = []
    // wx.getStorageInfo({
    //   // success(res) {
    //   //   var collcetKeys = res.keys
    //   //   var n = collcetKeys.length
    //   //   // if ((n == 2 && wx.getStorageSync("book")) || n == 1) { //判断缓存数据中是否有图片数据
    //   //   //   wx.showToast({
    //   //   //     title: '收藏夹中还没有图片，快去图库里逛逛吧(*^▽^*)(*^▽^*)',
    //   //   //     icon: 'none'
    //   //   //   })
    //   //   // } else {
    //   //   //   if (wx.getStorageSync("book")) {
    //   //   //     n = n - 3
    //   //   //   } else {
    //   //   //     n = n - 2
    //   //   //   }
    //   //   //   var m = 0
    //   //   //   for (var i = n; i >= 0; i--) {
    //   //   //     var a = {};
    //   //   //     a.img = wx.getStorageSync(collcetKeys[i])
    //   //   //     a.id = collcetKeys[i]
    //   //   //     collectData[m] = a
    //   //   //     m++
    //   //   //   }
    //   //   //   // that.setData({
    //   //   //   //   collcetData: collectData
    //   //   //   // })
    //   //   // }
    //   // }
    // })
  },
  //收藏页点击取消收藏按钮
  caneclCollect: function(e) {
    var that = this
    var img = e.target.dataset.url
    var contentlist = that.data.contentlist
    var collcetData = that.data.collcetData
    wx.showModal({
      title: '提示',
      content: '确认取消收藏吗？',
      showCancel: true,
      cancelText: '否',
      cancelColor: '#999',
      confirmText: '是',
      confirmColor: '#f94218',
      success(res) {
        if (res.confirm) {
          console.log('用户点击是')
          let index1 = collcetData.findIndex(item => item == img);
          let index0 = contentlist.findIndex(item => item.img == img);
          var photoCollcet = wx.getStorageSync("photoCollcet")

          let index2 = photoCollcet.findIndex(item => item == img); //更新缓存
          photoCollcet.splice(index2, 1)
          wx.setStorageSync("photoCollcet", photoCollcet)

          if (index0 != -1) { //更新图库数组
            contentlist[index0].collect = false //将图库中对应图片的收藏按钮改成空心
          }
          collcetData.splice(index1, 1) //更新收藏夹数组
          that.setData({
            collcetData: collcetData,
            contentlist: contentlist
          })
        } else if (res.cancel) {
          console.log('用户点击否')
        }
      }
    })
  }
})